<?php

//靓号
namespace App\Http\Controllers\Admin\Mall;


use App\Enums\MallEnum;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GoodCodeController extends BaseController
{
    /**
     * @api {Get} /mall/good-code/list 靓号列表
     *
     * @apiGroup 个性商城-靓号管理
     *
     * @apiParam {Int} cate1_id 父分类id，0：不限制，其它的根据接口
     * @apiParam {Int} cate2_id 子分类id，0：不限制，其它的根据接口
     * @apiParam {String} expire_date 过期日期，yyyy-mm-dd
     * @apiParam {Int} status 出售状态：0：不限制（默认）；1：上架；2：下架；
     * @apiParam {String} good_code 靓号
     * @apiParam {Int} price 价格
     * @apiParam {String} add_date 上架日期，yyyy-mm-dd
     * @apiParam {Int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 360, 序号
    "product_name": "666666", 靓号
    "category_id": 13,
    "on_sale": 2, 销售状态：1：上架；2：下架
    "remark": '使用中', 当on_sale=2时有值
    "expire_time": "2021-05-19 00:31:20", 过期时间，当on_sale=2的时候才有，‘过期时间’列展示该字段
    "add_time": "2021-05-18 13:21:20", 上架时间
    "product_price": [ 靓号价格信息：当on_sale=2的时候‘过期时间’列展示该字段
    {
    "day": 8, 天数
    "price": 1000 价格
    }
    ],
    "cate1_name": "S级号", 类别1名称
    "cate2_name": "S级" 类别2名称
    }
    ],
    "first_page_url": "http://local.qipaoadmin/mall/good-code/list?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/mall/good-code/list?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/mall/good-code/list",
    "per_page": 15,
    "prev_page_url": null,
    "to": 2,
    "total": 2
    }
    }
     */
    public function list(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'cate1_id' => 'integer',
                'cate2_id' => 'integer',
                'expire_date' => 'date',
                'status' => 'integer|in:0,1,2,3',
                'good_code' => 'integer',
                'price' => 'integer',
                'add_date' => 'date',
                'page_size' => 'integer|min:1',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $cate1Id = $request->cate1_id;
        $cate2Id = $request->cate2_id;
        $expireDate = $request->expire_date;
        $status = $request->status ?: 0;
        $goodCode = $request->good_code;
        $price = $request->price;
        $addDate = $request->add_date;
        $pageSize = $request->page_size ?: 10;

        //靓号对应的所有分类id
        $cateIds = app('model_mall_categories')->getAllSubCateId(MallEnum::PRODUCT_CATE_ID_GOOD_CODE);

        $where = $whereFunc = $whereFunc2 = $whereFunc3 = [];
        if ($cate1Id > 0) {
            //查询子分类
            $subCateIds = app('model_mall_categories')->where('parent_id', $cate1Id)->pluck('id')->toArray();
            if ($subCateIds) {
                if ($cate2Id > 0) {
                    $where[] = ['category_id', '=', $cate2Id];
                } else {
                    $whereFunc = function ($query) use ($subCateIds) {
                        $query->whereIn('category_id', $subCateIds);
                    };
                }
            } else {
                $where[] = ['category_id', '=', $cate1Id];
            }
        } else {
            $whereFunc = function ($query) use ($cateIds) {
                $query->whereIn('category_id', $cateIds);
            };
        }
        if ($expireDate) {
            $productIds = app('model_mall_orders')->whereIn('category_id', $cateIds)->where('state', 1)->whereBetween('expired_time', [strtotime($expireDate . ' 0:0:0'), strtotime($expireDate . ' 23:59:59')])
                ->pluck('product_id');
            $whereFunc2 = function ($query) use ($productIds) {
                $query->whereIn('id', $productIds);
            };
        }
        if ($status > 0) {
            $where[] = ['on_sale', '=', $status];
        }
        if ($goodCode) {
            $where[] = ['title', '=', $goodCode];
        }
        if ($price) {
            $productIds = app('model_mall_products_price')->where('price', $price)->pluck('product_id');
            $whereFunc3 = function ($query) use ($productIds) {
                $query->whereIn('id', $productIds);
            };
        }
        if ($addDate) {
            $where[] = ['add_time', '>=', strtotime($addDate . ' 0:0:0')];
            $where[] = ['add_time', '<=', strtotime($addDate . ' 23:59:59')];
        }

        $list = app('model_mall_products')
            ->select('id', 'title as product_name', 'picture', 'category_id', 'on_sale', 'add_time')
            ->where($where)
            ->where($whereFunc)
            ->where($whereFunc2)
            ->where($whereFunc3)
            ->paginate($pageSize)->toArray();
        $cateIds = array_column($list['data'], 'category_id');
        $catesName = app('repo_good_code')->getCatesName($cateIds);

        foreach ($list['data'] as &$v) {
            //添加时间
            $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
            //商品天数和价格信息
            $v['product_price']= $pricePrice = app('model_mall_products_price')
                ->select('day', 'price')
                ->where('product_id', $v['id'])
                ->get();
            //分类名称
            $v['cate1_name'] = $catesName[$v['category_id']]['cate1_name'];
            $v['cate2_name'] = $catesName[$v['category_id']]['cate2_name'];
            //过期时间
            if ($v['on_sale'] == 2) { //下架状态查询是否在使用中
                $v['remark'] = '';
                $v['expire_time'] = '';
                $order = app('model_mall_orders')
                    ->select('expired_time')
                    ->where('product_id', $v['id'])
                    ->whereIn('state', [0, 1])->first();
                if ($order) {
                    $v['remark'] = '使用中';
                    if ($order->expired_time == -1) {
                        $v['expire_time'] = '永久';
                    } else {
                        $v['expire_time'] = date('Y-m-d H:i:s', $order->expired_time);
                    }
                }
            }
        }
        return Response::sendData($list);
    }

    /**
     * @api {Post} /mall/good-code/add 添加靓号
     *
     * @apiGroup 个性商城-靓号管理
     *
     * @apiParam {Int} good_code 靓号，必须
     * @apiParam {Int} cate1_id 一级分类id，必须
     * @apiParam {Int} cate2_id 二级分类id，除叠字号之外必须
     * @apiParam {String} sale_status 销售状态：1：上架；2：下架，必须
     * @apiParam {String} picture 靓号图片url，必须
     * @apiParam {String} days_price 天数和价格信息，json格式，day：天数（永久的话传9999），price：价格，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function add(Request $request)
    {
        $overlapCodeCateId = MallEnum::PRODUCT_CATE_ID_S_LEVEL . ',' . MallEnum::PRODUCT_CATE_ID_LOVE;
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'good_code' => 'required|integer',
                'cate1_id' => 'required|integer|min:1',
                'cate2_id' => "required_if:cate1_id,{$overlapCodeCateId}|integer",
                'sale_status' => 'integer|in:1,2',
                'days_price' => 'string'
            ], [
                'cate2_id.required_if' => 'S级号和爱情号必须选择二级分类',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        return app('repo_good_code')->addOrEdit($request->all());
    }

    /**
     * @api {put} /mall/good-code/edit 编辑靓号
     *
     * @apiGroup 个性商城-靓号管理
     *
     * @apiParam {Int} id 编号id，必须
     * @apiParam {Int} good_code 靓号，必须
     * @apiParam {Int} cate1_id 一级分类id，必须
     * @apiParam {Int} cate2_id 二级分类id，必须
     * @apiParam {Int} sale_status 销售状态：1：上架；2：下架，必须
     * @apiParam {String} picture 靓号图片url，必须
     * @apiParam {String} days_price 天数和价格信息，json格式，day：天数（永久的话传9999），price：价格，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function edit(Request $request)
    {
        $overlapCodeCateId = MallEnum::PRODUCT_CATE_ID_S_LEVEL . ',' . MallEnum::PRODUCT_CATE_ID_LOVE;
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|integer|min:1',
                'good_code' => 'required|integer',
                'cate1_id' => 'required|integer|min:1',
                'cate2_id' => "required_if:cate1_id,{$overlapCodeCateId}|integer",
                'sale_status' => 'integer|in:1,2',
                'days_price' => 'string'
            ], [
                'cate2_id.required_if' => 'S级号和爱情号必须选择二级分类',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        return app('repo_good_code')->addOrEdit($request->all());
    }

    /**
     * @api {Get} /mall/good-code/buy-record 靓号购买记录
     *
     * @apiGroup 个性商城-靓号管理
     *
     * @apiParam {Int} cate1_id 父分类id，0：不限制，其它的根据接口
     * @apiParam {Int} cate2_id 子分类id，0：不限制，其它的根据接口
     * @apiParam {Int} good_code 靓号
     * @apiParam {String} buy_date 购买日期，yyyy-mm-dd
     * @apiParam {String} expire_date 过期日期，yyyy-mm-dd
     * @apiParam {Int} user_code 用户ID
     * @apiParam {String} nickname 用户昵称
     * @apiParam {Int} price 价格
     * @apiParam {Int} page_size 每页显示条数，默认10
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 2885, 序号
    "user_id_buyer": 547900,
    "product_id": 361,
    "price_id": 334,
    "category_id": 13,
    "add_time": "2021-07-05 16:17:59", 购买时间
    "expired_time": "2021-08-04 16:17:59", 到期时间
    "user_code": 617040, 用户ID
    "user_nickname": "提莫队长呢", 用户昵称
    "good_code": "777777", 靓号
    "good_code_price": 1000, 靓号价格
    "cate1_name": "S级号", 分类1名称
    "cate2_name": "S" 分类2名称
    }
    ],
    "first_page_url": "http://local.qipaoadmin/mall/good-code/buy-record?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/mall/good-code/buy-record?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/mall/good-code/buy-record",
    "per_page": 15,
    "prev_page_url": null,
    "to": 1,
    "total": 1
    }
    }
     */
    public function buyRecord(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'cate1_id' => 'integer',
                'cate2_id' => 'integer',
                'good_code' => 'integer',
                'buy_date' => 'date',
                'expire_date' => 'date',
                'user_code' => 'integer',
                'nickname' => 'string',
                'price' => 'integer',
                'page_size' => 'integer|min:1',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());
        $sortExpireTime = $request->input('order_expire_time', -1);
        $sortAddTime = $request->input('order_add_time', -1);

        $cate1Id = $request->cate1_id;
        $cate2Id = $request->cate2_id;
        $goodCode = $request->good_code;
        $buyDate = $request->buy_date;
        $expireDate = $request->expire_date;
        $userCode = $request->user_code;
        $nickname = $request->nickname;
        $price = $request->price;
        $pageSize = $request->page_size;

        $where = $whereFunc = $whereFunc2 = [];
        if ($cate1Id) {
            //查询子分类
            $cate2Ids = app('model_mall_categories')->where('parent_id', $cate1Id)->pluck('id')->toArray();

            if ($cate2Id) {
                $where[] = ['category_id', '=', $cate2Id];
            } else {
                if ($cate2Ids) {
                    $whereFunc = function ($query) use ($cate2Ids) {
                        $query->whereIn('category_id', $cate2Ids);
                    };
                } else {
                    $where[] = ['category_id', '=', $cate1Id];
                }
            }
        } else {
            $cateIds = app('model_mall_categories')->getAllSubCateId(MallEnum::PRODUCT_CATE_ID_GOOD_CODE);
            $whereFunc = function ($query) use ($cateIds) {
                $query->whereIn('category_id', $cateIds);
            };
        }
        if ($goodCode) {
            $productId = app('model_mall_products')->where('title', $goodCode)->value('id');
            $where[] = ['product_id', '=', $productId];
        }
        if ($buyDate) {
            $where[] = ['add_time', '>=', strtotime($buyDate . ' 0:0:0')];
            $where[] = ['add_time', '<=', strtotime($buyDate . ' 23:59:59')];
        }
        if ($expireDate) {
            $where[] = ['expired_time', '>=', strtotime($expireDate . ' 0:0:0')];
            $where[] = ['expired_time', '<=', strtotime($expireDate . ' 23:59:59')];
        }
        if ($userCode) {
            $userId = app('model_user_data')->where('user_code', $userCode)->value('user_id');
            if ($userId) {
                $where[] = ['user_id_buyer', '=', $userId];
            } else {
                $where[] = ['user_id_buyer', '=', 0];
            }
        }
        if ($nickname) {
            $userId = app('model_user_data')->where('nickname', $nickname)->value('user_id');
            if ($userId) {
                $where[] = ['user_id_buyer', '=', $userId];
            } else {
                $where[] = ['user_id_buyer', '=', 0];
            }
        }
        if ($price) {
            $productIds = app('model_mall_products_price')->where('price', $price)->pluck('product_id');
            $whereFunc2 = function ($query) use ($productIds) {
                $query->whereIn('product_id', $productIds);
            };
        }

        $obj = app('model_mall_orders');
        $permanentTime = 9999999999;
        $obj = $obj->select('id', 'user_id_buyer', 'product_id', 'price_id', 'category_id', 'price as good_code_price', 'add_time', DB::raw("IF(expired_time=-1,$permanentTime,expired_time) as expired_time") )
            ->where($where)
            ->where($whereFunc)
            ->where($whereFunc2);
        if($sortExpireTime >= 0 && in_array($sortExpireTime, [0,1])){
            $expTimeSortValue = $sortExpireTime == 0 ? 'asc' : 'desc';
            $obj = $obj->orderBy('expired_time', $expTimeSortValue);
        }
        if($sortAddTime >= 0 && in_array($sortAddTime, [0,1])){
            $addTimeSortValue = $sortAddTime == 0 ? 'asc' : 'desc';
            $obj = $obj->orderBy('add_time', $addTimeSortValue);
        }
        $list = $obj->paginate($pageSize)->toArray();
        //查询用户信息
        $userIds = array_unique(array_column($list['data'], 'user_id_buyer'));
        $users = app('model_user_data')->select('user_id', 'user_code', 'nickname')->whereIn('user_id', $userIds)->get()->toArray();
        $users = array_column($users, null, 'user_id');

        //查询商品信息
        $productIds = array_unique(array_column($list['data'], 'product_id'));
        $products = app('model_mall_products')->select('id', 'title')->whereIn('id', $productIds)->pluck('title', 'id');

        //查询商品所属分类信息
        $cateIds = array_unique(array_column($list['data'], 'category_id'));
        $catesName = app('repo_good_code')->getCatesName($cateIds);

        foreach ($list['data'] as &$v) {
            //用户code和昵称
            if (isset($users[$v['user_id_buyer']])) {
                $v['user_code'] = $users[$v['user_id_buyer']]['user_code'];
                $v['user_nickname'] = $users[$v['user_id_buyer']]['nickname'];
            } else {
                $v['user_code'] = '';
                $v['user_nickname'] = '';
            }
            //靓号名称
            $v['good_code'] = $products[$v['product_id']];
            //靓号一级和二级分类名称
            $v['cate1_name'] = $catesName[$v['category_id']]['cate1_name'];
            $v['cate2_name'] = $catesName[$v['category_id']]['cate2_name'];
            //购买和过期时间
            $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
            if($v['expired_time'] == $permanentTime){
                $v['expired_time'] = '永久';
            }else{
                $v['expired_time'] = date('Y-m-d H:i:s', $v['expired_time']);
            }
        }
        return Response::sendData($list);
    }
}